package top.jx.file;

import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import top.jx.dao.FileInfoDao;
import top.jx.model.FileInfo;
import top.opm.config.FileServiceConfig;
import top.opm.config.LocalFilePatch;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.UUID;

@Component
public class FileService {
    @Value(value = "${temporaryFile.path}")
    private String temporaryFilePath;

    @Autowired
    private FileServiceConfig fileServiceConfig;

    @Autowired
    private  LocalFilePatch localFilePatch;
    @Autowired
    private FileInfoDao fileInfoDao;


    public String getTempFilePath(String format) {
        return temporaryFilePath + "/" + String.valueOf(UUID.randomUUID()) + format;
    }
    public File getTempFile(String format) {
        return new File(temporaryFilePath + "/" + String.valueOf(UUID.randomUUID()) + format);
    }


    @SneakyThrows
    public FileInfo saveLocalPath(File sourceFile, String type){
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        String fileSuffix = FileUtil.getFileSuffix(sourceFile);
        File file = new File(localFilePatch.getRootPath() + "/" + sourceFile.getName() + fileSuffix);
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        IOUtils.copyLarge(fileInputStream, fileOutputStream);

        FileInfo fileInfo = new FileInfo();
        fileInfo.setPath(localFilePatch.getRootPath() + "/");
        fileInfo.setName(file.getName());
        fileInfo.setSuffix(FileUtil.getFileSuffix(file));
        fileInfo.setSize(FileUtil.getFileSize(file));
        fileInfo.setType(type);
        fileInfoDao.save(fileInfo);
        return fileInfo;
    }
}
